package com.gitee.form_token.controller;

import cn.hutool.json.JSONUtil;
import com.gitee.form_token.common.Const;
import com.gitee.form_token.common.Result;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
public class MyErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public void handleError(HttpServletRequest request, HttpServletResponse response) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        try {
            int statusCode = Integer.parseInt(status.toString());
            System.out.println("statusCode==" + statusCode);
            String msg = Const.getMsg(statusCode);
            returnMsg(msg, response);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 认证失败 -- 返回前端提示
     *
     * @param errorMsg
     * @param response
     * @throws IOException
     */
    private void returnMsg(String errorMsg, HttpServletResponse response) throws IOException {
        // response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(response.getStatus());
        Result result = Result.fail(errorMsg, response.getStatus());
        
        ServletOutputStream stream = response.getOutputStream();
        stream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        stream.flush();
        stream.close();
    }
}